import { ShellUtil } from "./ShellUtil";
import * as fs from "fs";

/**
 * svn更新
 * @author 
 */
export class SvnUtil {
    /** 更新（清空，还原式更新） */
    static update(svnUrl:string, path: string, cb: () => void) {
        console.log("update svn ", path);
        this.checkSvnExist(svnUrl, path, ()=>{
            ShellUtil.exec(`
                    svn cleanup ${path} || exit 1
                    svn stat ${path} | grep \\? | awk '{print $2}' | xargs rm -rf || exit 1
                    svn revert -R ${path}  || exit 1
                    # svn update ${path} || exit 1
                `, (log) => {
                console.log(log);
                ShellUtil.spawn("svn", ["update", path], cb);
            });
        })
    }
    /** 提交 */
    static commit(path: string, cb: () => void) {
        ShellUtil.exec(`
        cd ${path} || exit 1
        svn stat | grep \\! | awk '{print $2"@"}' | xargs svn remove || exit 1
        svn stat | grep \\? | awk '{print $2"@"}' | xargs svn add || exit 1
        # svn commit -m "脚本自动上传" || exit 1
        `, (log) => {
            console.log(log);
            ShellUtil.spawn("svn", ["commit", path, "-m", "脚本自动上传"], cb);
            // console.log(log);
            // cb();
        });
    }
    /**
     * 获取svn版本号
     */
    static getVersion(path: string, cb: (ver: string) => void) {
        ShellUtil.exec(`
            cd ${path} || exit 1
            svnversion -c |sed 's/^.*://' |sed 's/[A-Z]*$//' || exit
        `, (ver) => {
            cb(ver.trim());
        });
    };
    /**
     * 获取工作区文件变更状态
     */
    static status(path: string, cb: (status: string) => void) {
        ShellUtil.exec(`
            cd ${path} || exit 1
            svn status || exit
        `, (status) => {
            cb(status.trim());
        });
    };
    /**
     * 检测文件夹是否存在，如果不存在，则checkout
     */
    static checkSvnExist(svnUrl:string, path: string, cb: () => void) {
        if (fs.existsSync(path)) {
            cb();
        } else {
            ShellUtil.spawn("svn", ["checkout", svnUrl, path], cb);
        }
    }
}